<template>
  <table class="formtable" style="background-color:transparent; margin-bottom:5px; width:800px" name="routes" id="routes">
    <tr>
      <td align="center" style="width:40px" class="bgGray"><span>DAY</span></td>
      <td align="center" class="bgGray">行程描述</td>
    </tr>
    <tr v-for="(rows,i) in cmsRoutes" :key="i">
      <td align="center" class="bgGray"> DAY{{i+1}} </td>
      <td class="value">
        <div>
          <span>短标：</span>
          <!--短标数据-->
          <span v-for="(mark, plidx) in shortMark[i]" :key="plidx">
            <span style="margin: 0 3px" v-if="plidx > 0">
              <JDictSelectTag dictCode="traffic" size="small"
                v-model:value="mark.trf"
                :styler="{ width:'130px' }"
                :showArrow="true"
                :allowClear="false"
                :getPopupContainer="(node) => node.parentNode"
                :dropdownStyle="{ width: '100px', overflow: 'auto' }"
                @select="setTraffic(i)"
              >
              </JDictSelectTag>
            </span>
            <a-input style="width: 100px" placeholder="输入地点" v-model:value="mark.pla" @blur="setTraffic(i)"/>
          </span>
          <span style="margin-left: 10px; margin-top: -20px; display: inline-flex">
            <a-button color="success" size="small" @click="preparePlace(i)" preIcon="ant-design:plus-outlined" class="p-2"></a-button>
          </span>
          <a-input v-show="false" v-model:value="rows.traffic" ></a-input>
        </div>
        <div style="margin-top:2px;">
            住宿：<a-input name="routes['+i+'].stay" style="width: 235px" v-model:value="rows.stay" datatype="*" autocomplete="off" />
            <label style="margin-left:15px;">用餐：</label>
            早 <a-select size="small" v-model:value="rows.breakfast" :allowClear="false" :options="dinnerOptions" style="width: 65px; margin-right: 2px"></a-select>
            中 <a-select size="small" v-model:value="rows.lunch" :allowClear="false" :options="dinnerOptions" style="width: 65px; margin-right: 2px"></a-select>
            晚 <a-select size="small" v-model:value="rows.dinner" :allowClear="false" :options="dinnerOptions" style="width: 65px; margin-right: 2px"></a-select>
        </div>
        <div style="margin-top:2px;">
            景点：<a-input style="width: 350px" v-model:value="rows.viewspot" autocomplete="false"/>
            <label style="margin-left:15px; color: red">说明：多个景点名称，请用空格隔开</label>
        </div>
        <div style="margin-top:2px;">
          <JEditor :height="300" v-model:value="rows.detail"></JEditor>
        </div>
        <div class="inPic" style="margin-top: 5px">
          <JImageUpload bizPath="routes"
            :params="{ articleId: articleId, routeId: rows.id }"
            :fileMax="3"
            :addUrl="cmsPhotoUploadUrl"
            :delUrl="cmsPhotoDel"
            v-model:value="cmsPhotos[i]"
          >
          </JImageUpload>
        </div>
      </td>
      </tr>
  </table>
</template>

<script lang="ts" setup>
import { ref, computed, unref, reactive, watch, onMounted, nextTick, watchEffect } from "vue";
import { SearchOutlined } from '@ant-design/icons-vue';
import JImageUpload from "/@/components/Form/src/jeecg/components/JImageUpload.vue";
import JDictSelectTag from "/@/components/Form/src/jeecg/components/JDictSelectTag.vue";
import { cmsRouteList, cmsPhotoUploadUrl, cmsPhotoDel } from "/@/views/weixin/article/artticle.api";
import { propTypes } from "/@/utils/propTypes";
import { JEditor } from '/@/components/Form';
import type { SelectProps } from 'ant-design-vue';
import { isSpecialChar } from "/@/api/common/api";
import { SelectValue } from "ant-design-vue/es/select";

interface RouteInfo {
  id: string;
  photos: any[];
  traffic: string;
  stay: string;
  breakfast: string;
  lunch: string;
  dinner: string;
  viewspot: string;
  detail: string;
}

//传入参数
const props = defineProps({
  articleId: propTypes.string.def(''),
  days: propTypes.oneOfType([propTypes.string, propTypes.number]),
});

const emit = defineEmits(['change', 'update:value']);

//用餐
const dinnerOptions = ref<SelectValue>([
  { value: '0', label: "自理" },
  { value: '1', label: "包含" },
]);

//行程数据
const cmsRoutes = reactive<any>([])
//短标
const shortMark = reactive<any>([])
//行程图片
const cmsPhotos = reactive<any>([])

//初始化
watch(
  () => props.articleId,
  (visible) => {
    if (visible) {
      nextTick(() => initCmsRoutes())
    }
  },
  {
    deep: true,
    immediate: true
  }
);

/**
 * 监听selectValues变化
 */
watch(
  cmsRoutes,
  () => {
    if (cmsRoutes) {
      emit("change", cmsRoutes);
    }
  },
  {
    deep: true,
    immediate: false
  }
);

// onMounted(async () => {
//   await nextTick(() => {
//     initCmsRoutes();
//   });
// });

/**
 * 行程数据初始化
 */
async function initCmsRoutes() {
  //console.info("initCmsRoutes@@", props.articleId)
  var params = {articleId: props.articleId};
  await cmsRouteList(params).then((list) => {
    try {
      cmsRoutes.length = 0
      //实计已录入行程
      let rowsL = list ? list.length : 0;
      let days  = Number(props.days) || 0;

      if (days == 0) {
        return;
      }

      //如果设置的行程天数据，小于已录入行程，得取设置值显示
      if (rowsL >= days) {
        rowsL = days
      }

      for (var k = 0; k < rowsL ; k++) {
        cmsRoutes.push(list[k])
      }
      //console.info("cmsRouteList@@k", cmsRoutes)

      //新增的行程
      for (var i = rowsL; i < days ; i++) {
        let empty: RouteInfo = {
          id: '',
          photos: [],
          traffic: '',
          stay: '',
          breakfast: '0',
          lunch: '0',
          dinner: '0',
          viewspot: '',
          detail: '',
        };
        cmsRoutes.push(empty)
      }
      //console.info("cmsRouteList@@i", cmsRoutes)
      //emit("change", cmsRoutes);

      //短标初始化---------------------------
      let result:any[] = [];
      for (var routes of cmsRoutes) {
        let mark: { trf: string; pla: string }[] = [];
        let traffics = []
        if (routes && routes.traffic) {
          traffics = routes.traffic.split(">")
        } else {
          mark.push({
            trf: '',
            pla: ''
          })
        }
        for (let index = 0; index < traffics.length; index++) {
          if(index == 0) {
            mark.push({
              trf: '',
              pla: traffics[index]
            })
          } else {
            let aa = traffics[index].split(":")
            mark.push({
              trf: aa[0],
              pla: aa[1]
            })
          }
        }
        result.push(mark);
      }
      Object.assign(shortMark, result);
      //console.info("cmsRouteList@@traffics", shortMark)
      //短程图片
      let tempPhotos:any[] = [];
      for (var routes of cmsRoutes) {
        if (routes && routes.photos) {
          tempPhotos.push(routes.photos);
        }
      }
      
      Object.assign(cmsPhotos, tempPhotos);

    } catch (e) {
      alert("initCmsRoutes: " + e);
      return false;
    }
  })
}

function initPhotos(obj) {
  return unref(obj);
}

//短标 如：南宁 | 南宁>1:三亚>1:北京 = ["南宁"] | ["南宁", "1:三亚", "1:北京"]
let places = reactive<any>([[],[]])
function taffer(traffic) {
  places = traffic.split(">");
}

/**
 * 添加地点 - 点击添加组件
 * @param i
 */
function preparePlace(i) {
  addPlace('','',i);
}

/**
 * 添加地点 - 添加数据
 * @param tl 交通工具
 * @param pla 地点
 */
function addPlace(tl, pla, idx) {
  //交通工具
  shortMark[idx].push({ trf: '', pla: ''});
}

//设置行程短标值
function setTraffic(idx) {
  //console.info("setTraffic@@@", idx)
  let trafficShortMark = shortMark[idx], len;
  if (null != trafficShortMark && (len = trafficShortMark.length) > 0 ) {
    let traffic = trafficShortMark[0].pla;
    for (var i = 1; i < len; i++) {
      let pla = trafficShortMark[i].pla;
      if(!pla){
        continue
      }
      //第一项没有交通
      let trf = trafficShortMark[i].trf;
      traffic += ">" + trf + ":" + pla;
      //console.info(traffic)
    }
    console.info("setTraffic", traffic);
    cmsRoutes[idx].traffic = traffic
  }
}

//规定行程中景点格式，不能字母、数字、特殊字符
function orderViewspot(me) {
  var v = me.value;
  if(!v) return false
  isSpecialChar({ 'text': v }).then((res) => {
    if(!res.success) {
      alert((res['msg']))
    }
  })
}
</script>

<style lang="less" scoped>
@import "../cmsArticle.css";
</style>
